<template>
    <div class="filesystem-config">
        <div class="config-content">
            <div class="config-layout">
                <!-- 左侧驱动类型列表 -->
                <div class="driver-list">
                    <div class="driver-list-header">
                        <h4>存储驱动</h4>
                        <span class="driver-count">{{ configList.length }} 种类型</span>
                    </div>
                    <div class="driver-items">
                        <div v-for="config in configList" :key="config.disk_name" :class="[
                            'driver-item',
                            { 'active': currentConfig.disk_name === config.disk_name },
                            { 'enabled': config.status === 1 }
                        ]" @click="setCurrentConfig(config)">
                            <div class="driver-icon">
                                <i :class="getDriverIcon(config.disk_type)"></i>
                            </div>
                            <div class="driver-info">
                                <div class="driver-name">{{ getDriverLabel(config.disk_type) }}</div>
                                <div class="driver-disk">{{ config.disk_name }}</div>
                            </div>
                            <div class="driver-status" v-if="config.status === 1">
                                <el-tag type="success" size="small" effect="plain">当前使用</el-tag>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 右侧配置表单 -->
                <div class="config-form-container">
                    <div v-if="currentConfig.disk_name" class="config-form">
                        <div class="form-header row y_center" style="gap: 6px;">
                            <h4>{{ getDriverLabel(currentConfig.disk_type) }} 配置</h4>
                            <span class="form-subtitle">{{ currentConfig.disk_name }}</span>
                        </div>

                        <el-form :model="currentConfig" :rules="formRules" ref="configForm" label-width="100px"
                            size="default" :key="currentConfig.disk_name" style="padding-right: 40px;">
                            <el-form-item label="驱动类型" prop="disk_type">
                                        <el-select v-model="currentConfig.disk_type" placeholder="请选择驱动类型" disabled>
                                            <el-option v-for="option in availableDriverTypes" :key="option.value"
                                                :label="option.label" :value="option.value" />
                                        </el-select>
                                    </el-form-item>

                            <el-row :gutter="20">
                                <el-col :span="24">
                                    <el-form-item label="状态" prop="status">
                                        <el-switch v-model="currentConfig.status" :active-value="1" :inactive-value="0"
                                            active-text="启用" inactive-text="禁用" />
                                       
                                    </el-form-item>
                                </el-col>
                            </el-row>

                            <!-- 配置数据JSON编辑 -->
                            <el-row>
                                <el-col :span="24">
                                    <el-form-item label="配置数据" prop="config_data">
                                        <el-input v-model="currentConfig.config_data" type="textarea" :rows="16"
                                            placeholder="请输入JSON格式的配置数据" clearable />
                                        <div style="margin-top: 8px; color: #909399; font-size: 12px;">
                                            请输入有效的JSON格式配置数据，例如：{"key": "value", "port": 80}
                                        </div>
                                    </el-form-item>
                                </el-col>
                            </el-row>

                            <el-row>
                                <el-col :span="24">
                                    <el-form-item label="备注" prop="remark">
                                        <el-input v-model="currentConfig.remark" type="textarea" :rows="3"
                                            placeholder="请输入配置备注信息" />
                                    </el-form-item>
                                </el-col>
                            </el-row>
                        </el-form>

                        <div class="form-actions">
                            <el-button type="primary" @click="saveConfig" :loading="saving">
                                <i class="el-icon-check"></i>
                                保存配置
                            </el-button>
                            <el-button @click="resetConfig">
                                <i class="el-icon-refresh"></i>
                                重置
                            </el-button>
                        </div>
                    </div>

                    <!-- 未选择配置时的提示 -->
                    <div v-else class="empty-state">
                        <div class="empty-icon">
                            <i class="el-icon-folder-opened"></i>
                        </div>
                        <div class="empty-text">
                            <h4>请选择存储驱动</h4>
                            <p>从左侧列表中选择一个存储驱动来查看和编辑其配置</p>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
import { useAttachmentStore } from "../../../../stores/attachment"
import { ElMessage } from 'element-plus'

export default {
    name: 'filesystemConfig',
    data() {
        return {
            configList: [],
            currentConfig: {
                disk_name: '',
                disk_type: '',
                config_data: '',
                status: 0,
                remark: ''
            },
            originalConfig: {},
            saving: false,
            formRules: {
                disk_name: [
                    { required: true, message: '磁盘名称不能为空', trigger: 'blur' }
                ],
                disk_type: [
                    { required: true, message: '驱动类型不能为空', trigger: 'change' }
                ]
            },

        }
    },
    computed: {
        attachmentStore() {
            return useAttachmentStore()
        },

        // 从配置列表中获取可用的驱动类型
        availableDriverTypes() {
            const driverTypes = []
            const seenTypes = new Set()

            this.configList.forEach(config => {
                if (!seenTypes.has(config.disk_type)) {
                    seenTypes.add(config.disk_type)
                    driverTypes.push({
                        value: config.disk_type,
                        label: this.getDriverLabel(config.disk_type)
                    })
                }
            })

            return driverTypes
        }
    },
    async created() {
        await this.loadConfigs()
    },
    methods: {
        async loadConfigs() {
            try {
                const response = await this.attachmentStore.getFilesystemConfigs()
                this.configList = response || []

                if (this.configList.length > 0) {
                    // 优先选择启用的配置，如果没有则选择第一个
                    const activeConfig = this.configList.find(c => c.status === 1)
                    this.setCurrentConfig(activeConfig || this.configList[0])
                }
            } catch (error) {
                ElMessage.error('加载配置失败: ' + (error.message || '未知错误'))
            }
        },

        setCurrentConfig(config) {
            // 将config_data转换为JSON字符串用于编辑
            let configDataStr = ''
            if (config.config_data) {
                if (typeof config.config_data === 'string') {
                    configDataStr = config.config_data
                } else {
                    configDataStr = JSON.stringify(config.config_data, null, 2)
                }
            }

            this.currentConfig = {
                disk_name: config.disk_name,
                disk_type: config.disk_type,
                config_data: configDataStr,
                status: config.status,
                remark: config.remark || ''
            }
            this.originalConfig = JSON.parse(JSON.stringify(this.currentConfig))
        },

        async saveConfig() {
            try {
                await this.$refs.configForm.validate()

                // 验证JSON格式
                if (this.currentConfig.config_data.trim()) {
                    try {
                        JSON.parse(this.currentConfig.config_data)
                    } catch (e) {
                        ElMessage.error('配置数据格式错误，请输入有效的JSON格式')
                        return
                    }
                }

                this.saving = true

                // 准备提交的数据
                const submitData = {
                    disk_name: this.currentConfig.disk_name,
                    disk_type: this.currentConfig.disk_type,
                    config_data: this.currentConfig.config_data,
                    status: this.currentConfig.status,
                    remark: this.currentConfig.remark
                }

                await this.attachmentStore.updateFilesystemConfig(submitData)

                // 更新本地配置列表
                const index = this.configList.findIndex(c => c.disk_name === this.currentConfig.disk_name)
                if (index !== -1) {
                    // 如果当前配置被启用，需要禁用其他所有配置
                    if (this.currentConfig.status === 1) {
                        this.configList.forEach((config, i) => {
                            if (i !== index) {
                                config.status = 0
                            }
                        })
                    }

                    this.configList[index] = {
                        ...this.configList[index],
                        disk_type: this.currentConfig.disk_type,
                        config_data: this.currentConfig.config_data,
                        status: this.currentConfig.status,
                        remark: this.currentConfig.remark
                    }
                }

                this.originalConfig = JSON.parse(JSON.stringify(this.currentConfig))
                ElMessage.success('配置保存成功')
            } catch (error) {
                ElMessage.error('配置保存失败: ' + (error.message || '未知错误'))
            } finally {
                this.saving = false
            }
        },

        resetConfig() {
            this.currentConfig = JSON.parse(JSON.stringify(this.originalConfig))
            this.$refs.configForm?.clearValidate()
        },

        getDriverLabel(driver) {
            const labels = {
                local: '本地存储',
                aliyun: '阿里云OSS',
                qiniu: '七牛云',
                qcloud: '腾讯云COS',
                obs: '华为云OBS',
                s3: 'Amazon S3',
                google: 'Google Cloud',
                ftp: 'FTP',
                sftp: 'SFTP'
            }
            return labels[driver] || driver.toUpperCase()
        },

        getDriverIcon(driver) {
            const icons = {
                local: 'el-icon-folder',
                aliyun: 'el-icon-cloudy',
                qiniu: 'el-icon-cloudy',
                qcloud: 'el-icon-cloudy',
                obs: 'el-icon-cloudy',
                s3: 'el-icon-cloudy',
                google: 'el-icon-cloudy',
                ftp: 'el-icon-connection',
                sftp: 'el-icon-connection'
            }
            return icons[driver] || 'el-icon-files'
        }
    }
}
</script>

<style lang="less" scoped>
.filesystem-config {
    height: 100%;

    .config-content {
        height: 100%;

        .config-layout {
            display: flex;
            height: 100%;
            gap: 10px;

            // 左侧驱动列表
            .driver-list {
                width: 280px;
                background: #fff;
                border: 1px solid #ebeef5;
                border-radius: 8px;
                overflow: hidden;

                .driver-list-header {
                    padding: 16px 20px;
                    background: #f8f9fa;
                    border-bottom: 1px solid #ebeef5;
                    display: flex;
                    justify-content: space-between;
                    align-items: center;

                    h4 {
                        margin: 0;
                        font-size: 16px;
                        font-weight: 600;
                        color: #303133;
                    }

                    .driver-count {
                        font-size: 12px;
                        color: #909399;
                        background: #e4e7ed;
                        padding: 2px 8px;
                        border-radius: 12px;
                    }
                }

                .driver-items {
                    max-height: calc(100% - 60px);
                    overflow-y: auto;

                    .driver-item {
                        display: flex;
                        align-items: center;
                        padding: 16px 20px;
                        border-bottom: 1px solid #f5f7fa;
                        cursor: pointer;
                        transition: all 0.3s ease;
                        position: relative;

                        &:hover {
                            background: #f8f9fa;
                        }

                        &.active {
                            background: #ecf5ff;
                            border-left: 3px solid #409eff;

                            &::before {
                                content: '';
                                position: absolute;
                                right: 13px;
                                top: 15px;
                                transform: translateY(-50%);
                                width: 6px;
                                height: 6px;
                                background: #409eff;
                                border-radius: 50%;
                            }
                        }

                        &.enabled {
                            .driver-name {
                                font-weight: 600;
                                color: #67c23a;
                            }
                        }

                        .driver-icon {
                            width: 40px;
                            height: 40px;
                            border-radius: 8px;
                            background: #f0f2f5;
                            display: flex;
                            align-items: center;
                            justify-content: center;
                            margin-right: 12px;

                            i {
                                font-size: 18px;
                                color: #606266;
                            }
                        }

                        &.enabled .driver-icon {
                            background: #e8f5e8;

                            i {
                                color: #67c23a;
                            }
                        }

                        .driver-info {
                            flex: 1;
                            min-width: 0;

                            .driver-name {
                                font-size: 14px;
                                color: #303133;
                                margin-bottom: 4px;
                                font-weight: 500;
                            }

                            .driver-disk {
                                font-size: 12px;
                                color: #909399;
                                overflow: hidden;
                                text-overflow: ellipsis;
                                white-space: nowrap;
                            }
                        }

                        .driver-status {
                            display: flex;
                            flex-direction: column;
                            gap: 4px;
                            align-items: flex-end;
                        }
                    }
                }
            }

            // 右侧配置表单
            .config-form-container {
                flex: 1;
                background: #fff;
                border: 1px solid #ebeef5;
                border-radius: 8px;
                overflow: hidden;

                .config-form {
                    height: 100%;
                    display: flex;
                    flex-direction: column;

                    .form-header {
                        padding: 14px;
                        border-bottom: 1px solid #ebeef5;
                        background: #fafafa;

                        h4 {
                            margin: 0 0 4px 0;
                            font-size: 16px;
                            font-weight: 600;
                            color: #303133;
                        }

                        .form-subtitle {
                            font-size: 12px;
                            color: #909399;
                        }
                    }

                    .el-form {
                        flex: 1;
                        padding: 24px;
                        overflow-y: auto;

                        .el-form-item {
                            margin-bottom: 10px;

                            :deep(.el-form-item__label) {
                                font-weight: 500;
                                color: #606266;
                            }
                        }
                    }

                    .form-actions {
                        padding: 10px 24px;
                        border-top: 1px solid #ebeef5;
                        background: #fafafa;
                        text-align: right;

                        .el-button {
                            margin-left: 12px;

                            i {
                                margin-right: 4px;
                            }
                        }
                    }
                }

                .empty-state {
                    height: 100%;
                    display: flex;
                    flex-direction: column;
                    align-items: center;
                    justify-content: center;
                    color: #909399;

                    .empty-icon {
                        font-size: 64px;
                        margin-bottom: 16px;
                        opacity: 0.5;
                    }

                    .empty-text {
                        text-align: center;

                        h4 {
                            margin: 0 0 8px 0;
                            font-size: 16px;
                            color: #606266;
                        }

                        p {
                            margin: 0;
                            font-size: 14px;
                            color: #909399;
                        }
                    }
                }
            }
        }
    }
}

// 响应式设计
@media (max-width: 1200px) {
    .filesystem-config {
        .config-content {
            .config-layout {
                .driver-list {
                    width: 280px;
                }
            }
        }
    }
}

@media (max-width: 768px) {
    .filesystem-config {
        .config-content {
            .config-layout {
                flex-direction: column;

                .driver-list {
                    width: 100%;
                    height: 300px;
                }

                .config-form-container {
                    height: calc(100% - 320px);
                }
            }
        }
    }
}
</style>